//封装购物车模块
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
import { useUserStore } from './user'
import {insertCartAPI,findNewCartListAPI,delCartAPI} from '@/apis/cart'

export const useCartStore = defineStore('cart',() => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])

  const upDataNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }

  const addCart = async (goods) => {
    const {skuId,count} = goods
    if (isLogin.value) {
      //登陆之后的加入购物车逻辑
     await insertCartAPI({skuId,count})
     upDataNewList()
    }else {
      const item = cartList.value.find(item => item.skuId === goods.skuId)
    if (item) {
      item.count += goods.count
    } else {
      cartList.value.push(goods)
    }
  }
    }

  //删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
    //登陆之后的删除购物车逻辑
     await delCartAPI([skuId])
     upDataNewList()
    }else {
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  //清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  //单选功能
  const singleCheck = (skuId,selected) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }
  //全选功能
  const allCheck = (selected) => {
    cartList.value.forEach(item => {
      item.selected = selected
    })
  }

  //计算
  //1.总的数量
  const allCount =  computed(() => {
    return cartList.value.reduce((total, item) => total + item.count, 0)
  })
  //2.总价
  const allPrice =  computed(() => {
    return cartList.value.reduce((total, item) => total + item.count * item.price, 0)
  })
  //3.已选中数量
  const selectedCount = computed(() => {
    return cartList.value.reduce((total, item) => total + (item.selected ? item.count : 0), 0)
  })
  //4.已选中总价
  const selectedPrice = computed(() => {
    return cartList.value.reduce((total, item) => total + (item.selected ? item.count * item.price : 0), 0)
  })

  //是否全选
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected)
  })


  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    isAll,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCart,
    upDataNewList
  }
},
  { persist: true }
)
